<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>AI表情包生成器</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        #userInput {
            flex: 1;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        #response {
            white-space: pre-wrap;
            border: 2px solid #ddd;
            padding: 15px;
            margin-top: 20px;
            min-height: 100px;
            border-radius: 5px;
            background-color: white;
        }
        #imageContainer {
            margin-top: 20px;
            text-align: center;
        }
        #imageContainer img {
            max-width: 100%;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        .loading {
            color: #666;
            text-align: center;
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🎭 AI表情包生成器</h1>
        <div class="input-group">
            <input type="text" id="userInput" placeholder="描述你想要的表情包效果..." >
            <button onclick="sendRequest()">生成</button>
        </div>
        <div id="response" class="loading"></div>
        <div id="imageContainer"></div>
    </div>

    <script>
        // 处理流式响应数据
        async function processStreamResponse(response) {
            const reader = response.body.getReader();
            let buffer = '';
            let allContent = [];
            let isComplete = false;
            let imageUrl = null;

            // 处理单行数据
            function processLine(line) {
                if (line.trim() === '') return;
                
                try {
                    if (line.startsWith('event:')) {
                        console.log('事件:', line);
                        if (line.includes('conversation.message.end')) {
                            isComplete = true;
                        }
                        return;
                    }

                    const jsonStr = line.startsWith('data:') ? line.slice(5) : line;
                    const data = JSON.parse(jsonStr);
                    console.log('解析的数据:', data);
                    
                    if (data.event === 'conversation.message.delta' && data.data?.content) {
                        // 尝试从内容中提取图片URL
                        const content = data.data.content;
                        if (content.includes('http') && (content.includes('.jpg') || content.includes('.png') || content.includes('.gif'))) {
                            const urlMatch = content.match(/(https?:\/\/[^\s]+\.(jpg|png|gif))/i);
                            if (urlMatch) {
                                imageUrl = urlMatch[0];
                                console.log('找到图片URL:', imageUrl);
                            }
                        }
                        allContent.push(content);
                    }
                } catch (e) {
                    console.warn('解析失败:', line, e);
                }
            }

            while (true) {
                const {done, value} = await reader.read();
                if (done) break;

                buffer += new TextDecoder().decode(value);

                while (buffer.includes('\n')) {
                    const newlineIndex = buffer.indexOf('\n');
                    processLine(buffer.slice(0, newlineIndex));
                    buffer = buffer.slice(newlineIndex + 1);
                }
            }

            if (buffer.trim()) {
                processLine(buffer);
            }

            return {
                content: isComplete ? allContent.join('') : null,
                imageUrl: imageUrl
            };
        }

        async function sendRequest() {
            const userInput = document.getElementById('userInput').value;
            const responseDiv = document.getElementById('response');
            const imageContainer = document.getElementById('imageContainer');
            
            responseDiv.textContent = '正在生成表情包...';
            imageContainer.innerHTML = '';

            const requestBody = {
                bot_id: "7507834834912526373",
                user_id: "123456789",
                stream: true,
                auto_save_history: true,
                additional_messages: [
                    {
                        role: "user",
                        content: userInput,
                        content_type: "text"
                    }
                ]
            };

            try {
                const response = await fetch('https://api.coze.cn/v3/chat', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer pat_NY1YFME7UjXFikQQaA4pC6CwkQOKO7n4Ett6TWum3JN6ooXjG9FxWfVyO0q8e98N',
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await processStreamResponse(response);
                
                if (result.imageUrl) {
                    // 创建并显示图片
                    const img = document.createElement('img');
                    img.src = result.imageUrl;
                    img.alt = '生成的表情包';
                    imageContainer.appendChild(img);
                    responseDiv.textContent = '表情包生成完成！';
                } else {
                    responseDiv.textContent = result.content || '未能生成表情包，请重试';
                }

            } catch (error) {
                responseDiv.textContent = `错误: ${error.message}`;
                console.error('Error:', error);
            }
        }
    </script>
</body>
</html>